package resource

import (
	"net/http"
	"strings"

	request "github.com/infraboard/mcube/http/request"
)

const (
	AppName = "resource"
)

func NewResourceSet() *ResourceSet {
	return &ResourceSet{
		Items: []*Resource{},
	}
}

func NewDefaultResource() *Resource {
	return &Resource{
		Base: &Base{},
		Information: &Information{
			Tags: map[string]string{},
		},
		ReleasePlan: &ReleasePlan{},
	}
}

func (i *Information) LoadPrivateIPString(ips string) {
	i.PrivateIp = strings.Split(ips, ",")
}

func (i *Information) PublicIPToString() string {
	return strings.Join(i.PublicIp, ",")
}

func (i *Information) LoadPublicIPString(ips string) {
	i.PublicIp = strings.Split(ips, ",")
}

func (i *Information) PrivateIPToString() string {
	return strings.Join(i.PrivateIp, ",")
}

func (s *ResourceSet) Add(item *Resource) {
	s.Items = append(s.Items, item)
}

func NewSearchRequestFromHTTP(r *http.Request) (*SearchRequest, error) {
	qs := r.URL.Query()

	req := &SearchRequest{
		Page:     request.NewPageRequestFromHTTP(r),
		Keywords: qs.Get("keywords"),
	}

	vendor := qs.Get("vendor")
	if vendor != "" {
		v, err := ParseVendorFromString(vendor)
		if err != nil {
			return nil, err
		}
		req.Vendor = &v
	}

	rt := qs.Get("type")
	if rt != "" {
		v, err := ParseTypeFromString(rt)
		if err != nil {
			return nil, err
		}
		req.Type = &v
	}

	return req, nil
}
